package com.renjun.smweb.commons.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lrs on 2017/2/24.
 */
public class StringUtils {

    private static String dict = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";  //数据字典

    private static Random random = new Random();

    /**
     * 获取随机字符串
     * @author lrs
     * @param length 随机字符串长度
     * @return String
     */
    public static String getRandomStr(int length) throws Exception {
        if(length<0) throw new Exception("字符串长度不能小于0");
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < length; i++) {
            sb.append(dict.charAt(random.nextInt(dict.length())));
        }
        return sb.toString();
    }

    /**
     * 将 clob 大字符类型转换为 String 类型
     * @param clob
     * @return String
     * @throws SQLException
     * @throws IOException
     */
    public static String clobToStr(Clob clob) throws SQLException, IOException {
        StringBuffer buffer = new StringBuffer();
        Reader reader = clob.getCharacterStream(); //初始化字符流
        BufferedReader br = new BufferedReader(reader);
        String readLine = br.readLine();
        while (!BaseChecks.hasEmptyStr(readLine)){
            buffer.append(readLine);
            readLine = br.readLine();
        }
        return buffer.toString();
    }

    /**
     *
     * 将list集合中的指定的 Clob 类型转换为 String 类型
     * @param result list集合
     * @param keys 参数名
     * @return 返回一个新的list集合
     * @throws IOException
     * @throws SQLException
     */
    public static List<Map<String,Object>> clobToStrForList(List<Map<String,Object>> result, String... keys) throws IOException, SQLException {
        for (Map<String,Object> map:result){
            for(String key:keys){
                if(map.get(key) instanceof Clob){
                    map.put(key,clobToStr((Clob)map.get(key)));
                }
            }
        }
        return result;
    }

    /**
     * 移除字符串的空格
     * @param str
     * @return
     */
    public static String removeEmptyCharsOfStr(String str){
        if(str==null) return "";
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if(m.find()){   //中文校验
            str = str.replace(" ","");
        }else{
            str = str.trim();
        }
        return str;
    }
}